package gui.admin;

import database.TableDatabaseUsage;
import gui.admin.mtm.ATM1;
import info.Flight;
import messages.flight.*;
import server.MessageServer;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.IOException;
import java.sql.Time;
import java.util.Calendar;


public class ManageFlights extends JFrame {
    JFrame jf = new JFrame();
    private String flights_id;
    private String date_time;
    private JTable jTable;
    private Flight cacheFlight = new Flight();

    public ManageFlights() {
        jTable = new JTable(ATM1.getInstance());
        //头部欢迎文字
        JPanel jp = new JPanel();
        jp.setBounds(240, 30, 500, 60);
        JLabel jL = new JLabel( "欢迎使用航班管理系统！");
        //创建文字对象

        jL.setFont(new Font("Serif", Font.BOLD, 33));
        jL.setForeground(Color.darkGray);
        jp.add(jL);
        jf.add(jp);

        JButton btn1 = new JButton("增加航班");
        JButton btn2 = new JButton("查询航班");
        JButton btn3 = new JButton("修改航班");
        JButton btn4 = new JButton("删除航班");
        JPanel panel = new JPanel();


        //按钮
        btn1.setBounds(100, 50, 125, 30);
        jf.getContentPane().add(btn1);

        btn1.addActionListener(e -> {
            // TODO Auto-generated method stub
            System.out.println("增加航班按钮被点击了！");
            new AddFlightsInfoForm(cacheFlight);

        });


        //查询按钮
        btn2.setBounds(100, 100, 125, 30);


        jf.getContentPane().add(btn2);
        //航班号
        JLabel FilghtNumLabel = new JLabel("航班号");
        FilghtNumLabel.setBounds(240, 100, 100, 30);

        JTextField flightNum = new JTextField("输入航班号");


        //监听事件：
        flightNum.addFocusListener(new FocusListener() {

            @Override
            public void focusLost(FocusEvent e) {
                //失去焦点时，用户尚未在文本框输入任何内容，依旧显示提示文字
                if (flightNum.getText().equals("")) {
                    flightNum.setForeground(Color.gray);
                    flightNum.setText("输入航班号");

                }

            }

            @Override
            public void focusGained(FocusEvent e) {
                //得到焦点时，文本框的提示文字和创建该对象时的提示文字一样，说明用户正要输入内容
                if (flightNum.getText().equals("输入航班号")) {
                    flightNum.setText("");
                    flightNum.setForeground(Color.black);
                }

            }
        });


        flightNum.setBounds(300, 98, 150, 35);

        jf.getContentPane().add(FilghtNumLabel);
        jf.getContentPane().add(flightNum);
        btn2.addActionListener(e->{
            System.out.println("查询航班按钮被点击了！");
            if(!flightNum.getText().equals("")&&!flightNum.getText().equals("输入航班号")) {
                flights_id = flightNum.getText();
                ATM1.getInstance().flightList= TableDatabaseUsage.getInstance().getFlightList1(flights_id);
//                start();
                flightNum.setText("输入航班号");
                jTable.updateUI();
            }

        });


        //修改按钮
        btn3.setBounds(100, 380, 125, 30);
        btn3.addActionListener(e -> {
            System.out.println("修改航班按钮被点击了！");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1){
                String flighted = (String) jTable.getValueAt(selectedRow,0);
                String DEPAed=(String) jTable.getValueAt(selectedRow,1);
                Time DEPATimed=(Time) jTable.getValueAt(selectedRow,2);
                String DESTed=(String) jTable.getValueAt(selectedRow,3);
                Time DESTTimed=(Time) jTable.getValueAt(selectedRow,4);
                Time Boardinged=(Time) jTable.getValueAt(selectedRow,5);
                int Gated=(int) jTable.getValueAt(selectedRow,6);


                System.out.println("你选择航班为"+flighted);
                cacheFlight.setFlight(flighted);
                cacheFlight.setDEPA(DEPAed);
                cacheFlight.setDEPATime(DEPATimed);
                cacheFlight.setDEST(DESTed);
                cacheFlight.setDESTTIME(DESTTimed);
                cacheFlight.setBoarding(Boardinged);
                cacheFlight.setGate(Gated);

                new UpdateFlightsInfoForm();
            }else {
                JOptionPane.showMessageDialog(null, "请选择一行进行修改！");
            }
        });
        jf.getContentPane().add(btn3);

        //删除按钮
        btn4.setBounds(260, 380, 125, 30);
        btn4.addActionListener(e -> {
            System.out.println("删除航班按钮被点击了！");
            int selectedRow=jTable.getSelectedRow();
            if(selectedRow!=-1){
                int response = JOptionPane.showConfirmDialog(null, "确认删除吗！", "删除确认", JOptionPane.YES_NO_OPTION);
                String flighted = (String) jTable.getValueAt(selectedRow,0);

                System.out.println("你删除航班为"+flighted);
                // 根据用户选择执行相应操作
                if (response == JOptionPane.YES_OPTION) {
                    // 用户选择了“是”，执行删除操作
                    System.out.println("用户确认删除");
                    JOptionPane.showMessageDialog(null, "删除成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
                    sendDeleteFlightsInfoMsg(flighted);
                    ATM1.getInstance().flightList=TableDatabaseUsage.getInstance().getFlightList();
                    jTable.updateUI();
                    // 在这里添加删除逻辑
                } else if (response == JOptionPane.NO_OPTION) {
                    // 用户选择了“否”，取消删除操作
                    System.out.println("用户取消删除");
                    JOptionPane.showMessageDialog(null, "您已取消删除！", "操作失败", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 用户关闭了对话框或点击了其他按钮（如果有）
                    System.out.println("用户关闭了对话框或点击了其他按钮");
                }

            }else {
                JOptionPane.showMessageDialog(null, "请选择一行进行删除！");
            }
        });
        jf.getContentPane().add(btn4);

        jf.getContentPane().add(panel);
        jf.setTitle("管理员—航班管理主界面");
        jf.setLocation(400, 300);
        jf.setSize(800, 500);

        //表格

//        JTable jTable = new JTable();
        JScrollPane scroll = new JScrollPane(jTable);

        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setPreferredSize(new Dimension(595, 200));
        jTable.setBackground(Color.white);
        jTable.setRowHeight(40);

        jTable.setGridColor(Color.pink);
        jTable.setSelectionBackground(Color.orange);
        //使表格文字居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();

        centerRenderer.setHorizontalAlignment(JLabel.CENTER);


        for (int i = 0; i < jTable.getColumnCount(); i++) {
            jTable.getColumnModel().getColumn(i).setCellRenderer(centerRenderer);

        }


        panel.setBorder(BorderFactory.createEmptyBorder(150, 0, 0, 0));



        panel.add(scroll);
        jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        jf.setResizable(false);
        jf.setVisible(true);
    }
    private Flight cacheFLight = new Flight();
    class AddFlightsInfoForm extends JFrame {
        JTextField FlightIdTextField;
        JTextField DEPATextField ;
        JTextField DEPATimeTextField ;
        JTextField DESTTextField ;
        JTextField DESTimeTextField ;
        JTextField BoardingTextField ;
        JTextField GateTextField ;


        private Flight newFlight = new Flight();

        public AddFlightsInfoForm(Flight flight) {
            super("增加航班信息");
            setSize(500, 500);
            setLayout(new GridLayout(8, 2));
            FlightIdTextField = new JTextField(flight.getFlight());
            DEPATextField  = new JTextField(flight.getDEPA());
            DEPATimeTextField  = new JTextField(String.valueOf(flight.getDEPATime()));
            DESTTextField  = new JTextField(flight.getDEST());
            DESTimeTextField  = new JTextField(String.valueOf(flight.getDEPATime()));
            BoardingTextField  = new JTextField(String.valueOf(flight.getBoarding()));
            GateTextField  = new JTextField(flight.getGate());
            JButton AddInfoButton = new JButton("确认增加");
            AddInfoButton.addActionListener(e -> {
                newFlight.setFlight(FlightIdTextField.getText());
                newFlight.setDEPA(DEPATextField.getText());
                newFlight.setDEPATime(Time.valueOf(DEPATimeTextField.getText()));

                newFlight.setDEST(DESTTextField.getText());
                newFlight.setDESTTIME(Time.valueOf(DESTimeTextField.getText()));
                newFlight.setBoarding(Time.valueOf(BoardingTextField.getText()));

                int gate =  Integer.parseInt(GateTextField.getText());
                newFlight.setGate(gate);
                sendAddFlightsInfoMsg(newFlight);
                JOptionPane.showMessageDialog(null, "操作成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
//                if(sendAddFlightsInfoMsg(newFlight)){
//                    JOptionPane.showMessageDialog(null, "操作成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
//                    FlightIdTextField.setText("");
//                    DEPATextField.setText("");
//                    DEPATimeTextField.setText("");
//                    DESTTextField.setText("");
//                    DESTimeTextField.setText("");
//                    BoardingTextField.setText("");
//                    GateTextField.setText("");
//                }else{
//                    JOptionPane.showMessageDialog(null, "操作失败，请重试。", "错误", JOptionPane.ERROR_MESSAGE);
//                }

                dispose();
            });

            JLabel l1 = new JLabel("航班号：");
            JLabel l2 = new JLabel("起飞站：");
            JLabel l3 = new JLabel("起飞时间：");
            JLabel l4 = new JLabel("到达站：");
            JLabel l5 = new JLabel("到达时间：");
            JLabel l6 = new JLabel("登机时间：");
            JLabel l7 = new JLabel("登机口：");


            // 设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);
            l6.setHorizontalAlignment(JLabel.CENTER);
            l7.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(FlightIdTextField);
            add(l2);
            add(DEPATextField);
            add(l3);
            add(DEPATimeTextField);
            add(l4);
            add(DESTTextField);
            add(l5);
            add(DESTimeTextField);
            add(l6);
            add(BoardingTextField);
            add(l7);
            add(GateTextField);

            add(new JLabel(""));
            add(AddInfoButton);

            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);


        }
        private boolean sendAddFlightsInfoMsg(Flight newFlight) {
            AddInfoRequestMessage addInfoRequestMessage = new AddInfoRequestMessage(newFlight);
            AddInfoResponeMessage addInfoResponeMessage;
            addInfoRequestMessage.setFlights(newFlight);
            try {
                MessageServer.getInstance().getOos().writeObject(addInfoRequestMessage);
                System.out.println("客户端发送请求成功！"+addInfoRequestMessage);
                addInfoResponeMessage = (AddInfoResponeMessage) MessageServer.getInstance().
                        getOis().readObject();
                System.out.println("客户端收到服务端的响应成功！"+addInfoResponeMessage);
                return true;
            } catch (IOException | ClassNotFoundException e) {
                System.out.println("请求超时");
                throw new RuntimeException(e);

            }

        }

    }

    //    private Flight cacheFlight1=new Flight();
    class UpdateFlightsInfoForm extends JFrame {
        JTextField FlightIdTextField;
        JTextField DEPATextField;
        JTextField DEPATimeTextField;
        JTextField DESTTextField;
        JTextField DESTimeTextField;
        JTextField BoardingTextField;
        JTextField GateTextField;
        private String oldFlightId;
        private Flight newflight = new Flight();

        public UpdateFlightsInfoForm() {
            super("修改航班信息");
            setSize(500, 500);
            setLayout(new GridLayout(8, 2));
            oldFlightId=cacheFlight.getFlight();
            FlightIdTextField = new JTextField(cacheFlight.getFlight());
            DEPATextField = new JTextField(cacheFlight.getDEPA());
            DEPATimeTextField = new JTextField(String.valueOf(cacheFlight.getDEPATime()));
            DESTTextField = new JTextField(cacheFlight.getDEST());
            DESTimeTextField = new JTextField(String.valueOf(cacheFlight.getDESTTIME()));
            BoardingTextField = new JTextField(String.valueOf(cacheFlight.getBoarding()));
            GateTextField = new JTextField(String.valueOf(cacheFlight.getGate()));
            JButton updateInfoButton = new JButton("提交修改");
            updateInfoButton.addActionListener(e -> {
                newflight.setFlight(FlightIdTextField.getText());
                newflight.setDEPA(DEPATextField.getText());
                newflight.setDEPATime(Time.valueOf(DEPATimeTextField.getText()));
                newflight.setDEST(DESTTextField.getText());
                newflight.setDESTTIME(Time.valueOf(DESTimeTextField.getText()));
                newflight.setBoarding(Time.valueOf(BoardingTextField.getText()));
                int gate = Integer.parseInt(GateTextField.getText());
                newflight.setGate(gate);
                sendUpdateFlightsInfoMsg(newflight, oldFlightId);
                JOptionPane.showMessageDialog(null, "操作成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                //                if(sendAddFlightsInfoMsg(newFlight)){
                //                    JOptionPane.showMessageDialog(null, "操作成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                //                    FlightIdTextField.setText("");
                //                    DEPATextField.setText("");
                //                    DEPATimeTextField.setText("");
                //                    DESTTextField.setText("");
                //                    DESTimeTextField.setText("");
                //                    BoardingTextField.setText("");
                //                    GateTextField.setText("");
                //                }else{
                //                    JOptionPane.showMessageDialog(null, "操作失败，请重试。", "错误", JOptionPane.ERROR_MESSAGE);
                //                }

                dispose();
            });

            JLabel l1 = new JLabel("航班号：");
            JLabel l2 = new JLabel("起飞站：");
            JLabel l3 = new JLabel("起飞时间：");
            JLabel l4 = new JLabel("到达站：");
            JLabel l5 = new JLabel("到达时间：");
            JLabel l6 = new JLabel("登机时间：");
            JLabel l7 = new JLabel("登机口：");


            // 设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);
            l6.setHorizontalAlignment(JLabel.CENTER);
            l7.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(FlightIdTextField);
            add(l2);
            add(DEPATextField);
            add(l3);
            add(DEPATimeTextField);
            add(l4);
            add(DESTTextField);
            add(l5);
            add(DESTimeTextField);
            add(l6);
            add(BoardingTextField);
            add(l7);
            add(GateTextField);

            add(new JLabel(""));
            add(updateInfoButton);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);
        }
        private boolean sendUpdateFlightsInfoMsg(Flight flight,String OldFlightId){
            UPFliInfoRequestMessage upFlightInfoRequestMessage = new UPFliInfoRequestMessage(flight);
            UPFLliInfoResponseMessage upfLliInfoResponseMessage;
            upFlightInfoRequestMessage.setFlight(flight);
            upFlightInfoRequestMessage.setOldFliId(OldFlightId);

            try {
                MessageServer.getInstance().getOos().writeObject(upFlightInfoRequestMessage);
                System.out.println("客户端发送请求成功！"+upFlightInfoRequestMessage);
                upfLliInfoResponseMessage = (UPFLliInfoResponseMessage) MessageServer.getInstance().
                        getOis().readObject();
                System.out.println("客户端收到服务端的响应成功！"+upfLliInfoResponseMessage);
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            updateFliInfo(upfLliInfoResponseMessage.getNewFlight());
            return true;
        }

        private void updateFliInfo(Flight newFlight){
            cacheFLight.setFlight(newFlight.getFlight());
            cacheFLight.setDEPA(newFlight.getDEPA());
            cacheFLight.setDEPATime(newFlight.getDEPATime());
            cacheFLight.setDEST(newFlight.getDEST());
            cacheFLight.setDESTTIME(newFlight.getDESTTIME());
            cacheFLight.setBoarding(newFlight.getBoarding());
            cacheFLight.setGate(newFlight.getGate());

        }

    }
    private boolean sendDeleteFlightsInfoMsg(String OldFlightId){
        DeFliInfoRequestMessage deFlightInfoRequestMessage = new DeFliInfoRequestMessage();
        DeFLliInfoResponseMessage defLliInfoResponseMessage;
        deFlightInfoRequestMessage.setOldFliId(OldFlightId);
        try {
            MessageServer.getInstance().getOos().writeObject(deFlightInfoRequestMessage);
            System.out.println("客户端发送请求成功！"+deFlightInfoRequestMessage);
            defLliInfoResponseMessage = (DeFLliInfoResponseMessage) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+defLliInfoResponseMessage);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return true;
    }


}

